package cn.kxlove.zhbj.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

import cn.kxlove.zhbj.R;

/**
 * @author kxlove 16/1/28 16:56
 */
public class RefreshListView extends ListView implements AdapterView.OnItemClickListener,AbsListView.OnScrollListener{

    private static final int STATE_PULL_TO_REFRESH = 1;// 下拉刷新状态
    private static final int STATE_RELEASE_TO_REFRESH = 2;// 松开刷新状态
    private static final int STATE_REFRESHING = 3;// 正在刷新状态

    private int mCurrentState = STATE_PULL_TO_REFRESH;// 当前状态,默认是下拉刷新

    private View mHeaderView;
    private View mFooterView;

    private int mHeaderViewHeight;
    private int mFooterViewHeight;

    private OnRefreshListener mListener;

    private int startY = -1;

    private TextView tvTitle;
    private TextView tvTime;
    private ImageView ivArrow;
    private ProgressBar pbLoading;

    // 箭头动画
    private RotateAnimation animUp;
    private RotateAnimation animDown;

    private boolean isLoadingMore = false;// 是否正在加载更多

    public RefreshListView(Context context) {
        super(context);
        initHeaderView();
        initFooterView();
    }

    public RefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initHeaderView();
        initFooterView();
    }

    public RefreshListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initHeaderView();
        initFooterView();
    }

//    private void initView() {
//        mHeaderView = View.inflate(getContext(),
//                R.layout.pull_to_refresh_header, null);
//        this.addHeaderView(mHeaderView);// 给listview添加头布局
//
//        // 隐藏头布局
//        // 设置负的上边距, 从而布局就会向上走
//        int mHeaderViewHeight = mHeaderView.getHeight();
//        mHeaderView.measure(0, 0);// 手动测量布局宽高,具体宽高由系统底层决定
//        mHeaderViewHeight = mHeaderView.getMeasuredHeight();
//        System.out.println("height:" + mHeaderViewHeight);
//        mHeaderView.setPadding(0, -mHeaderViewHeight, 0, 0);
//    }

    /**
     * 初始化头布局
     */
    private void initHeaderView() {
        mHeaderView = View.inflate(getContext(),
                R.layout.pull_to_refresh_header, null);
        this.addHeaderView(mHeaderView);// 给listview添加头布局

        tvTitle = (TextView) mHeaderView.findViewById(R.id.tv_title);
        tvTime = (TextView) mHeaderView.findViewById(R.id.tv_time);
        ivArrow = (ImageView) mHeaderView.findViewById(R.id.iv_arrow);
        pbLoading = (ProgressBar) mHeaderView.findViewById(R.id.pb_loading);

        // 隐藏头布局
        // 设置负的上边距, 从而布局就会向上走
        // int mHeaderViewHeight = mHeaderView.getHeight();
        mHeaderView.measure(0, 0);// 手动测量布局宽高,具体宽高由系统底层决定
        mHeaderViewHeight = mHeaderView.getMeasuredHeight();
        System.out.println("height:" + mHeaderViewHeight);
        mHeaderView.setPadding(0, -mHeaderViewHeight, 0, 0);

        initAnim();
        setRefreshTime();
    }

    /**
     * 初始化脚布局
     */
    private void initFooterView() {
        mFooterView = View.inflate(getContext(),
                R.layout.pull_to_refresh_footer, null);
        this.addFooterView(mFooterView);

        // 隐藏脚布局
        mFooterView.measure(0, 0);
        mFooterViewHeight = mFooterView.getMeasuredHeight();
        mFooterView.setPadding(0, -mFooterViewHeight, 0, 0);

        this.setOnScrollListener(this);
    }

    /**
     * 初始化箭头动画
     */
    private void initAnim() {
        // 箭头向上
        animUp = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        animUp.setDuration(200);
        animUp.setFillAfter(true);// 保持动画结束后的状态

        // 箭头向下
        animDown = new RotateAnimation(-180, 0, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animDown.setDuration(200);
        animDown.setFillAfter(true);// 保持动画结束后的状态

    }


    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                startY = (int) ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (startY == -1) {// 当按住头条新闻下拉时,ACTION_DOWN会被viewpager消费掉,所以需要重新初始化startY
                    startY = (int) ev.getY();
                }

                int endY = (int) ev.getY();
                int dy = endY - startY;

                // 如果当前是正在刷新状态, 什么都不做
                if (mCurrentState == STATE_REFRESHING) {
                    break;// 跳出循环
                }

                int firstVisiblePosition = getFirstVisiblePosition();// 当前显示的第一个item的位置
                if (dy > 0 && firstVisiblePosition == 0) {// 下拉动作&当前在listview的最顶部
                    int paddingTop = dy - mHeaderViewHeight;// 计算当前控件的padding值

                    // System.out.println("paddingTop:" + paddingTop);

                    if (paddingTop < 0 && mCurrentState != STATE_PULL_TO_REFRESH) {// 当前不是下拉刷新时,更新为下拉刷新状态
                        // 下拉刷新的事件
                        mCurrentState = STATE_PULL_TO_REFRESH;
                        refreshState();
                    } else if (paddingTop >= 0
                            && mCurrentState != STATE_RELEASE_TO_REFRESH) {
                        // 松开刷新的事件
                        mCurrentState = STATE_RELEASE_TO_REFRESH;
                        refreshState();
                    }

                    mHeaderView.setPadding(0, paddingTop, 0, 0);// 设置控件padding,更新位置

                    return true;// 消费此事件
                }

                break;
            case MotionEvent.ACTION_UP:
                startY = -1;// 重新初始化起始坐标位置

                if (mCurrentState == STATE_RELEASE_TO_REFRESH) {// 如果当前是松开刷新状态,要切换为正在刷新
                    mCurrentState = STATE_REFRESHING;
                    // 完整展示正在刷新的控件
                    mHeaderView.setPadding(0, 0, 0, 0);
                    refreshState();

                    // 回调下拉刷新动作
                    if (mListener != null) {
                        mListener.onRefresh();
                    }
                } else if (mCurrentState == STATE_PULL_TO_REFRESH) {
                    // 隐藏控件
                    mHeaderView.setPadding(0, -mHeaderViewHeight, 0, 0);
                }

                break;

            default:
                break;
        }


        return super.onTouchEvent(ev);
    }

    private void refreshState() {

        switch (mCurrentState) {
            case STATE_PULL_TO_REFRESH:
                tvTitle.setText("下拉刷新");
                pbLoading.setVisibility(View.INVISIBLE);
                ivArrow.startAnimation(animDown);
                break;
            case STATE_RELEASE_TO_REFRESH:
                tvTitle.setText("松开刷新");
                pbLoading.setVisibility(View.INVISIBLE);
                ivArrow.startAnimation(animUp);
                break;
            case STATE_REFRESHING:
                tvTitle.setText("正在刷新...");
                pbLoading.setVisibility(View.VISIBLE);
                ivArrow.clearAnimation();// 必须先清除动画,才能够隐藏控件
                ivArrow.setVisibility(View.INVISIBLE);
                break;

            default:
                break;
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // 滑动状态发生变化
        if (scrollState == SCROLL_STATE_IDLE) {// listview空闲
            int lastVisiblePosition = getLastVisiblePosition();// 当前显示的最后一个item的位置
            if (lastVisiblePosition == getCount() - 1 && !isLoadingMore) {
                isLoadingMore = true;// 开始加载更多

                // 最底部了
                System.out.println("到底了...");
                mFooterView.setPadding(0, 0, 0, 0);// 显示脚布局
                this.setSelection(getCount() - 1);// 让listview显示在最后一个位置,直接显示脚布局

                // 访问网络数据
                if (mListener != null) {
                    mListener.loadMore();// 加载更多
                }
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    public interface OnRefreshListener {
        // 下拉刷新回调
        public void onRefresh();

        // 加载更多回调
        public void loadMore();
    }

    public void setOnRefreshListener(OnRefreshListener listener) {
        mListener = listener;
    }

    /**
     * 刷新结束
     */
    public void onRefreshComplete(boolean success) {
        System.out.println("isLoadingMore:" + isLoadingMore);

        if (!isLoadingMore) {
            // 隐藏控件
            mHeaderView.setPadding(0, -mHeaderViewHeight, 0, 0);

            // 设置为默认的下拉刷新状态
            mCurrentState = STATE_PULL_TO_REFRESH;
            tvTitle.setText("下拉刷新");
            pbLoading.setVisibility(View.INVISIBLE);
            ivArrow.startAnimation(animDown);

            if (success) {
                setRefreshTime();// 网络访问成功,才设置刷新时间
            }
        } else {
            // 加载更多
            isLoadingMore = false;
            mFooterView.setPadding(0, -mFooterViewHeight, 0, 0);// 隐藏更多
        }

    }

    private void setRefreshTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// H大写表示24小时制;h表示12小时制
        String time = format.format(new Date());
        tvTime.setText(time);
    }

    private OnItemClickListener mClickListener;

    @Override
    public void setOnItemClickListener(
            android.widget.AdapterView.OnItemClickListener listener) {
        mClickListener = listener;
        super.setOnItemClickListener(this);// 给当前下拉刷新控件来设置点击事件
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        // 通知前端界面,item被点击的事件, 回调
        if (mClickListener != null) {
            mClickListener.onItemClick(parent, view, position
                    - getHeaderViewsCount(), id);// 将position减掉头布局个数之后,回调给前端界面
        }
    }
}
